package com.mccken.rapid.core.netty;

import com.mccken.rapid.core.context.HttpRequestWrapper;
import com.mccken.rapid.core.netty.processor.NettyProcessor;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * netty核心处理handler
 * 
 * @program: rapid_gateway
 * @description:
 * @author: mccken
 * @create: 2022-01-03 19:50
 **/
@Slf4j
public class NettyHttpServerHandler extends ChannelInboundHandlerAdapter { // SimpleChannelInboundHandler
	
	private NettyProcessor processor;
	
	public NettyHttpServerHandler(NettyProcessor processor) {
		this.processor = processor;
	}

	/**
	 * 核心的请求处理类
	 * 
	 * @param ctx
	 * @param msg
	 * @throws Exception
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		
		if (msg instanceof HttpRequest) {
			FullHttpRequest request = (FullHttpRequest) msg;
			HttpRequestWrapper httpRequestWrapper = new HttpRequestWrapper();
			httpRequestWrapper.setFullHttpRequest(request);
			httpRequestWrapper.setCtx(ctx);
			
			// 交给执行器器
			processor.process(httpRequestWrapper);
			
		} else {
			// never go this way, ignore
			log.error("#NettyHttpServerHandler.channel# message type is not httpRequest: {}", msg);
			boolean release = ReferenceCountUtil.release(msg);
			if (!release) {
				log.error("#NettyHttpServerHandler.channel# release fail 资源释放失败");
			}
		}
		
		
	}
}
